﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Web;

namespace Amf4Asmx.Configuration
{
    public class ServiceHandlerMapping : ConfigurationElement
    {
        #region Key

        internal string Key
        {
            get
            {
                return ("contentType=" + this.ContentType);
            }
        }

        [ConfigurationProperty("contentType", IsRequired = true, IsKey = true)]
        public string ContentType
        {
            get
            {
                return (string)base["contentType"];
            }
            set
            {
                base["contentType"] = value;
            }
        }
        #endregion

        #region Type

        private Type _type;
        private string typeCache;

        [ConfigurationProperty("type", IsRequired = true)]
        public string Type
        {
            get
            {
                if (this.typeCache == null)
                {
                    this.typeCache = (string)base["type"];
                }
                return this.typeCache;
            }
            set
            {
                base["type"] = value;
                this.typeCache = value;
            }
        }

        internal Type TypeInternal
        {
            get
            {
                return this._type;
            }
        }
        #endregion

        internal bool IsMatch(string contentType)
        {
            return contentType.StartsWith(ContentType);
        }

        internal void InitValidateInternal()
        {
            this._type = System.Type.GetType(this.Type);
            if (this._type == null)
            {
                throw new ConfigurationErrorsException(string.Format("Could not find type {0}", this.Type), base.ElementInformation.Source, base.ElementInformation.LineNumber);
            }
            if (!Utils.IsTypeHandlerOrFactory(this._type))
            {
                throw new ConfigurationErrorsException(string.Format("Type {0} does not implement either IHttpHandler or IHttpHandlerFactory", this.Type), base.ElementInformation.Source, base.ElementInformation.LineNumber);
            }
        }
    }
}
